
package com.ng.sys.service.impl;

import java.util.Arrays;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ng.common.cache.annotation.TrCache;
import com.ng.common.cache.annotation.TrCacheEvict;
import com.ng.common.cache.annotation.TrCacheEvict.EvictType;
import com.ng.common.exception.NgException;
import com.ng.common.service.CacheServiceImpl;
import com.ng.common.utils.PageUtils;
import com.ng.common.utils.Query;
import com.ng.sys.dao.SysConfigDao;
import com.ng.sys.entity.SysConfigEntity;
import com.ng.sys.service.SysConfigService;

@Service
public class SysConfigServiceImpl extends CacheServiceImpl<SysConfigDao, SysConfigEntity> implements SysConfigService {
		@Override
	public PageUtils queryPage(SysConfigEntity entity , PageUtils page) {
		String paramKey = entity.getParamKey();

		IPage<SysConfigEntity> ipage = this.page(
				new Query<SysConfigEntity>(page).getPage(),
				new QueryWrapper<SysConfigEntity>()
					.like(StringUtils.isNotBlank(paramKey),"param_key", paramKey)
					.eq("status", 1)
		);

		return new PageUtils(ipage);
	}
	
	 

	@Override
	@TrCacheEvict(value="#key",type=EvictType.start)
	public void updateValueByKey(String key, String value) {
		
		SysConfigEntity config = new SysConfigEntity();
		config.setParamKey(key);
		config.setParamValue(value);
		
		updateById(config);
		 
	}

	@Override 
	@TrCacheEvict
	public void deleteBatch(String[] keys) {
		 
		this.removeByIds(Arrays.asList(keys));
	}

	@Override
	@TrCache(value="#key+ '.value'",cacheNull=true)
	public String getValue(String key) {
		SysConfigEntity config = getById(key);
		  
		return config == null ? null : config.getParamValue();
	}
	
	@Override
	@TrCache("#key + '.object'")
	public <T> T getConfigObject(String key, Class<T> clazz) {
		String value = getValue(key);
		if(StringUtils.isNotBlank(value)){
			return JSON.parseObject(value, clazz) ;// new Gson().fromJson(value, clazz);
		}

		try {
			return clazz.newInstance();
		} catch (Exception e) {
			throw new NgException("获取参数失败");
		}
	}
}
